package com.huluobo.a2204kotlinshopping.login

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.View.OnClickListener
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2204kotlinshopping.MainActivity
import com.huluobo.a2204kotlinshopping.R
import com.huluobo.a2204kotlinshopping.databinding.ActivityLoginBinding
import com.huluobo.a2204kotlinshopping.register.RegisterActivity
import com.huluobo.base.bean.UserBeanResult
import com.huluobo.base.db.AppDBUtils
import com.huluobo.base.net.Const
import com.huluobo.base.view.BaseMVVMActivity
import com.hyphenate.EMCallBack
import com.hyphenate.chat.EMClient

class LoginActivity : BaseMVVMActivity<ActivityLoginBinding, LoginViewModel>() {
    override fun initData() {
        viewModel.loginSuccess.observe(this) {
            if (it.code == 200) {
                //保存用户token
                SPUtils.getInstance().put(Const.PARAM_TOKEN, it.data.token)
                SPUtils.getInstance().put(Const.PARAM_USERNAME, it.data.username)
                AppDBUtils.getDb().userDao.insertUserInfo(it.data)

                EMClient.getInstance().login(it.data.username, it.data.password, object : EMCallBack {
                    override fun onSuccess() {
                        val intent = Intent(this@LoginActivity, MainActivity::class.java)
                        startActivity(intent)
                        this@LoginActivity.finish()
                    }

                    override fun onError(code: Int, error: String?) {
                        ToastUtils.showLong("登录环信失败:$code,$error")
                    }
                })

            } else {
                dataBinding.loginPasswordEt.error = it.message
            }
        }

        viewModel.loginFailed.observe(this) {
            Log.i("TagA", "登录失败:$it")
        }
    }

    override fun initView() {
        //触发登录
        dataBinding.loginToLoginBtn.setOnClickListener {
            viewModel.login(
                dataBinding.loginUsernameEt.text.toString(),
                dataBinding.loginPasswordEt.text.toString()
            )
        }

        dataBinding.loginRegisterTv.setOnClickListener {
            val intent = Intent(this, RegisterActivity::class.java)
            startActivity(intent)
        }
    }

    override fun getViewModel(): Class<LoginViewModel> {
        return LoginViewModel::class.java
    }

    override fun getLayoutId(): Int = R.layout.activity_login
}